package com.guage.task;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import com.guage.commons.utils.JsonUtils;
import com.guage.service.IRoleService;

/*@Lazy(false)*/
@Component
@EnableScheduling
public class BaiduBaikeJob implements SchedulingConfigurer {
	private static final Logger logger = LogManager.getLogger(BaiduBaikeJob.class);
    private String  cron = "0/5 * * * * ?";
    @Resource
	private IRoleService roleService;

	/*public IRoleService getRoleService() {
		return roleService1;
	}

	public void setRoleService(IRoleService roleService1) {
		this.roleService1 = roleService1;
		getCronDataToDBThreads();
	}
*/
	/* 构造函数注入 */
	/*public BaiduBaikeJob(IRoleService roleService) {
		this.roleService = roleService;
		logger.info("---------执行构造方法------------!");
	}*/
    @PostConstruct
    public void startSelectCronData(){
    	logger.info("---------执行init-method方法------------!");
    	getCronDataToDBThreads();
    }
	/**
	 * 获取数据库中的定时任务执行时间（正常）
	 */
	private void getCronDataToDBThreads() {
		ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
		executor.scheduleAtFixedRate(new Runnable() {
			public void run() {
				Object obj = roleService.selectTree();
				logger.info("getCronDataToDBThreads()数据库中获取的数据为：-----------"+JsonUtils.toJson(obj));
				cron = "0/10 * * * * ?";
				logger.info("当前cron修改为："+cron);
			}
		},0, 10, TimeUnit.SECONDS);
	}

	public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
		Trigger trigger = new Trigger() {
			public Date nextExecutionTime(TriggerContext triggerContext) {
				// 任务触发，可修改任务的执行周期
				CronTrigger trigger = new CronTrigger(cron);
				logger.info("最新的时间为:" + cron);
				Date nextExec = trigger.nextExecutionTime(triggerContext);
				return nextExec;
			}
		};
		taskRegistrar.addTriggerTask(new Runnable() {
			public void run() {
				Object obj = roleService.selectTree();
				logger.info("configureTasks()数据库中获取的数据为：-----------"+JsonUtils.toJson(obj));
				// 任务逻辑
				logger.debug("dynamicCronTask is running...");
			}
		}, trigger);
	}
}
